
app.admin = {}

/**
 * models
 */

app.admin.Company = Backbone.Model.extend({
	urlRoot : "api/company",
});

app.admin.CompanyCollection = Backbone.Collection.extend({
	url : "api/company",
	model : app.admin.Company
});

app.admin.User = Backbone.Model.extend({
	urlRoot : "api/user",
});

app.admin.UserCollection = Backbone.Collection.extend({
	url : "api/user",
	model : app.admin.User
});

app.admin.ProfilePatient = Backbone.Model.extend({
	urlRoot : "api/profilePatient",
});

app.admin.ProfilePatientCollection = Backbone.Collection.extend({
	url : "api/profilePatient",
	model : app.admin.ProfilePatient
});

/**
 * Views
 */

app.admin.AdminView = Backbone.View.extend({
	initialize: function () {},
	template: _.template( app.get("tpl/admin/admin.html") ),
	render: function () {
		if(app.admin.user)
		{
			$(this.el).html(this.template());
			this.renderUserList();
			this.renderCompanyEdit();
		}
		return this;
	},
	renderUserList : function() {
		var view = this;
		var userCollection = new app.admin.UserCollection();
		userCollection.fetch({
			data : {
				companyId : app.admin.user.get("companyId")
			},
			success : function( users ) {
				var userListView = new app.admin.UserListView({el : $('#userList', view.el), collection : userCollection });
				userListView.render();
			}
		});
	},
	renderCompanyEdit : function() {
		var company = new app.admin.Company({ id : app.admin.user.get("companyId") });
		var view = this;
		company.fetch({
			data : {},
			success : function( company ) {
				var companyEditView = new app.admin.CompanyEditView({el : $('#companyEdit', view.el), model : company });
				companyEditView.render();
			}
		});
	},
});

app.admin.CompanyEditView = Backbone.View.extend({
	template: _.template( app.get("tpl/admin/companyEdit.html") ),
	events: {
		'click button.save': 'save',
		//'click button.cancel': 'cancel',
		'change input' : 'onChange',
	},		
	render: function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	onChange: function() {
		this.model.set({ name : this.$('input.name').val() });
	},
	save: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response) {
			}
		});
	},
	//cancel: function () {},
	
});

app.admin.UserListView = Backbone.View.extend({
	template: _.template( app.get("tpl/admin/userList.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'appendItem');
	},
	render: function () {
		$(this.el).html(this.template());
		_.each(this.collection.models, this.appendItem, this);
		return this;
	},
	appendItem: function (user) {
		var userListItemView = new app.admin.UserListItemView({
			model : user,
		});
		userListItemView.userListView = this;
		$(".users tbody", this.el).append( userListItemView.render().el );
	},
	events: {
		'click button.create': 'create',
	},
	create: function() {
		var view = this;
		var user = new app.admin.User( { companyId : app.admin.user.get("companyId") } );
		this.collection.create(user, {
			success: function() {
				view.undelegateEvents();
				var userEditView = new app.admin.UserEditView({
					model: user,
					el : $(view.el)
				});
				userEditView.render();
			}
		});
	},
});

app.admin.UserListItemView = Backbone.View.extend({
	tagName:"tr",
	template: _.template( app.get("tpl/admin/userListItem.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'unrender', 'remove');
		this.model.bind('remove', this.unrender);
	},
	render:function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	unrender: function(){
		$(this.el).remove();
	},
	events: {
		'click a.delete': 'remove',
		'click a.edit': 'edit',
	},
	remove: function(e) {
		if(
			!$(e.currentTarget).hasClass("disabled")
			&&
			confirm("Deseja eliminar este cliente ?")
		) {
			this.model.destroy();
		};
	},
	edit: function(){
		this.userListView.undelegateEvents();
		var userEditView = new app.admin.UserEditView({
			model: this.model,
			el : $(this.userListView.el)
		});
		userEditView.render();
	},
	
});



app.admin.UserEditView = Backbone.View.extend({
	
	template: _.template( app.get("tpl/admin/userEdit.html") ),
	
	events: {
		'click button.save': 'save',
		'click button.cancel': 'cancel',
		'change input' : 'onChange',
		'click #tab-profilePatient-handle' : 'editProfilePatient'
	},
	
	render: function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	
	onChange: function(){
		this.model.set({ name : this.$('input.name').val() });
		this.model.set({ email : this.$('input.email').val() });
		this.model.set({ password : this.$('input.password').val() });
	},
	
	save: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response){
		    	var userCollection = new app.admin.UserCollection();
		    	userCollection.fetch({
					data : {
			    		companyId : app.admin.user.get("companyId") // self.model.get('companyId')
					},
					success : function( users ) {
						self.undelegateEvents();
						var userListView = new app.admin.UserListView({el : self.el, collection : users });
						userListView.render();
					}
				});
				
			}
		});
	},
	
	cancel: function () {
		var self = this;
    	var userCollection = new app.admin.UserCollection();
    	userCollection.fetch({
			data : {
	    		companyId : app.admin.user.get("companyId") // this.model.get('companyId')
			},
			success : function( users ) {
				self.undelegateEvents();
				if(self.profilePatientEditView != null) {
					self.profilePatientEditView.undelegateEvents();
				}
				var userListView = new app.admin.UserListView({el : self.el, collection : users });
				userListView.render();
			}
		});
	},
	
	editProfilePatient: function () {
		var self = this;
		if(this.profilePatientEditView == null) {
			var profilePatients = new app.admin.ProfilePatientCollection();
			profilePatients.fetch({
				data : {
					userId : this.model.get("id")
				},
				success : function( profilePatients ) {
					var profilePatient = profilePatients.at(0);
					if(!profilePatient) {
						profilePatient = new app.admin.ProfilePatient({userId : self.model.get("id")});
					}
					this.profilePatientEditView = new app.admin.ProfilePatientEditView({el : $('#tab-profilePatient'), model : profilePatient });
					this.profilePatientEditView.render();
				}
			});
		}
	},
	
});

app.admin.ProfilePatientEditView = Backbone.View.extend({
	
	template: _.template( app.get("tpl/admin/profilePatientEdit.html") ),
	
	events: {
		'click button.create': 'create',
		'change input' : 'onChange',
	},
	
	render: function () {
		$(this.el).html(this.template(this.model ? this.model.toJSON() : null));
		return this;
	},
	
	create: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response){
				self.render();
			}
		});
	},

	onChange: function(){
		this.model.set({ healthNumber : this.$('input.healthNumber').val() });
	},
	
});
